import os,inspect,random
from flask_script import Command, Option
from importlib import import_module
from flask import current_app
from faker.providers import internet

def load_command(manager,command_path=None):
    """自动加载自定义终端命令"""
    if command_path is None:
        command_path = manager.app.config["COMMAND_PATH"]

    module = import_module(command_path)
    class_list = inspect.getmembers(module, inspect.isclass)
    for class_item in class_list:
        if issubclass(class_item[1],Command) and class_item[0] != "Command":
            manager.add_command(class_item[1].name,class_item[1])

class BlueprintCommand(Command):
    """生成蓝图的终端命令"""

    # 终端调用别名
    name = "blue" # python manage.py blue

    # 参数列表
    option_list = [
        Option('--name', '-n', dest='name'),
    ]

    def run(self, name):
        # 生成蓝图名称对象的目录
        os.mkdir(name)
        open("%s/__init__.py" % name, "w")
        open("%s/views.py" % name, "w")
        open("%s/models.py" % name, "w")
        with open("%s/urls.py" % name, "w") as f:
            content = """from . import views
from application.utils import path
urlpatterns = [

]"""
            f.write(content)
        print("蓝图%s创建完成...." % name)

class FakerCommand(Command):
    """生成测试的工具类"""
    name = "faker"
    option_list = [
        Option('--type', '-t', dest='type',default="user"), # 生成数据的类型
        Option('--num', '-n', dest='num',default=1),   # 生成数据的数量
    ]

    type_list = [
        "user"
    ]

    def run(self, type, num):
        if type not in self.type_list:
            print("数据类型不正确\n当前Faker生成数据类型仅支持: %s" % self.type_list)
            return None
        num = int(num)
        if num < 1:
            print("生成数量不正确\n当前Faker生成数据至少1个以上")
            return None

        if type == "user":
            self.create_user(num)

    def create_user(self,num):
        """生成指定数量的测试用户信息"""
        with current_app.app_context():
            from application.apps.users.models import User, UserProfile,db
            faker = current_app.faker
            faker.add_provider(internet)

        user_list = []
        password = "123456"
        for _ in range(0, num):
            sex = bool(random.randint(0, 2))
            if sex:
                # 男生
                nickname = faker.name_male()
            else:
                nickname = faker.name_female()

            # 登录账号[随机字母,6-16位]
            name = faker.pystr(min_chars=6, max_chars=16)

            # 生成指定范围的时间对象
            age = random.randint(13, 50)
            birthday = faker.date_time_between(start_date="-%sy" % age, end_date="-12y", tzinfo=None)

            hometown_province = faker.province()
            hometown_city = faker.city()
            hometown_area = faker.district()

            living_province = faker.province()
            living_city = faker.city()
            living_area = faker.district()

            user = User(
                nickname=nickname,
                sex=sex,
                name=name,
                age=age,
                password=password,
                transation_password=password,
                money=random.randint(100, 99999),
                ip_address=faker.ipv4_public(),
                email=faker.ascii_free_email(),
                mobile=faker.phone_number(),
                unique_id=faker.uuid4(),
                province=faker.province(),
                city=faker.city(),
                area=faker.district(),
                info=UserProfile(
                    birthday=birthday,
                    hometown_province=hometown_province,
                    hometown_city=hometown_city,
                    hometown_area=hometown_area,
                    hometown_address=hometown_province + hometown_city + hometown_area + faker.street_address(),
                    living_province=living_province,
                    living_city=living_city,
                    living_area=living_area,
                    living_address=living_province + living_city + living_area + faker.street_address()
                )
            )

            user_list.append(user)

        db.session.add_all(user_list)
        db.session.commit()

        print("生成%s个用户信息完成..." % num)